from PySide6.QtWidgets import QToolBar
from PySide6.QtCore import Qt, QPoint
from PySide6.QtGui import QMouseEvent

class FloatingToolbar(QToolBar):
    def __init__(self, parent=None):
        super().__init__(parent)
        self.setMovable(True)
        self.setFloatable(True)
        self.setAllowedAreas(Qt.TopToolBarArea)
        self._drag_start_position = None

    def mousePressEvent(self, event: QMouseEvent):
        if event.button() == Qt.LeftButton:
            self._drag_start_position = event.position().toPoint()
        super().mousePressEvent(event)

    def mouseMoveEvent(self, event: QMouseEvent):
        if self._drag_start_position is not None:
            if not self.isFloating():
                # 计算移动距离
                diff = event.position().toPoint() - self._drag_start_position
                if diff.manhattanLength() > 10:  # 移动超过10像素才触发浮动
                    self.setFloating(True)
                    # 设置浮动位置
                    self.move(self.mapToGlobal(self._drag_start_position))
        super().mouseMoveEvent(event)

    def mouseReleaseEvent(self, event: QMouseEvent):
        self._drag_start_position = None
        super().mouseReleaseEvent(event)

    def moveEvent(self, event):
        if self.isFloating():
            # 获取主窗口
            main_window = self.parent()
            if main_window:
                # 获取菜单栏的位置和大小
                menu_bar = main_window.menuBar()
                menu_rect = menu_bar.geometry()
                menu_bottom = menu_rect.bottom()
                
                # 获取工具栏的位置
                toolbar_pos = self.pos()
                
                # 如果工具栏在菜单栏下方，则允许放置
                if toolbar_pos.y() >= menu_bottom:
                    super().moveEvent(event)
                else:
                    # 否则将工具栏移动到菜单栏下方
                    self.move(toolbar_pos.x(), menu_bottom + 10) 